import 'dart:convert';
import 'dart:developer';

import 'package:dio/dio.dart';
import 'package:ylm_ui_kit/ylm_ui_kit.dart';

class SeInterceptToCurl extends Interceptor {
  final bool? printOnSuccess;
  final bool convertFormData;

  SeInterceptToCurl({this.printOnSuccess, this.convertFormData = true});

  @override
  void onError(DioError err, ErrorInterceptorHandler handler) {
    _renderCurlRepresentation(err.requestOptions);

    return handler.next(err);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    if (printOnSuccess != null && printOnSuccess == true) {
      _renderCurlRepresentation(response.requestOptions);
    }

    return handler.next(response);
  }

  void _renderCurlRepresentation(RequestOptions requestOptions) {
    try {
      log(_cURLRepresentation(requestOptions));
    } catch (err) {}
  }

  String _cURLRepresentation(RequestOptions options) {
    List<String> components = ['curl -i'];
    if (options.method.toUpperCase() != 'GET') {
      components.add('-X ${options.method}');
    }

    options.headers.forEach((k, v) {
      if (k != 'Cookie') {
        components.add('-H "$k: $v"');
      }
    });

    if (options.data != null) {
      if (options.data is FormData && convertFormData == true) {
        options.data = Map.fromEntries(options.data.fields);
      }

      final data = json.encode(options.data).replaceAll('"', '\\"');
      components.add('-d "$data"');
    }

    components.add('"${options.uri.toString()}"');

    return components.join(' \\\n\t');
  }
}

///日志打印
class SeLogInterceptor extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    super.onRequest(options, handler);
    Log.log("call-${options.baseUrl}${options.path}");
    Log.log("call-${options.headers.toString()}");
    Log.log("call-${options.data}");
  }

  @override
  void onError(DioError err, ErrorInterceptorHandler handler) {
    super.onError(err, handler);
    Log.log("error-${err.requestOptions.baseUrl}${err.requestOptions.path}");
    Log.log("error-${err.message}");
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    super.onResponse(response, handler);
    Log.log("response-${response.requestOptions.baseUrl}${response.requestOptions.path}");
    Log.log("response-${response.data.runtimeType} : ${jsonEncode(response.data)}");
  }
}
